package cn.edu.ccibe.exam16system.controller;

import cn.edu.ccibe.exam16system.entity.form.LoginForm;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class AdminController {

    @GetMapping("/")
    public String index(Model model) {
        LoginForm loginForm = new LoginForm();
        model.addAttribute("adminLoginForm", loginForm);
        return "index";
    }

    @PostMapping("/adminLogin")
    public String adminLogin(HttpServletRequest request, @ModelAttribute LoginForm loginForm, Model model) {
        String username = loginForm.getUsername();
        String password = loginForm.getPassword();
        if ("admin".equals(username) && "123456".equals(password)) {
            model.addAttribute("redirectUrl", "/students");
            HttpSession session = request.getSession();
            session.setAttribute("loginUsername", "admin");
            session.setAttribute("isAdmin", true);
            return "redirect";
        } else {
            model.addAttribute("adminLoginForm", loginForm);
            model.addAttribute("loginError", "用户名或密码错误");
        }
        return "index";
    }

    @PostMapping("/doLogout")
    public String doLogout(HttpServletRequest request, Model model) {
        request.getSession().invalidate();
        model.addAttribute("redirectUrl", "/dormitory");
        return "redirect";
    }
}
